// 食谱控制器
const pool = require('../../database');

// 获取所有食谱
exports.getRecipes = async (req, res) => {
  try {
    const [rows] = await pool.query(`
      SELECT r.*, 
        GROUP_CONCAT(DISTINCT i.name SEPARATOR ', ') AS ingredients,
        n.calories, n.protein, n.fat, n.carbs
      FROM recipes r
      LEFT JOIN ingredients i ON r.id = i.recipe_id
      LEFT JOIN nutrition n ON r.id = n.recipe_id
      GROUP BY r.id
      LIMIT 20
    `);
    res.send({
      status: 200,
      message: '获取食谱成功！',
      data: rows,
    })
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

// 获取单个食谱
exports.getRecipeById = async (req, res) => {
  try {
    const [recipe] = await pool.query('SELECT * FROM recipes WHERE id = ?', [req.params.id]);

    if (!recipe.length) {
      return res.status(404).json({ error: 'Recipe not found' });
    }

    const [ingredients] = await pool.query('SELECT * FROM ingredients WHERE recipe_id = ?', [req.params.id]);
    const [steps] = await pool.query('SELECT * FROM steps WHERE recipe_id = ? ORDER BY step_number', [req.params.id]);
    const [nutrition] = await pool.query('SELECT * FROM nutrition WHERE recipe_id = ?', [req.params.id]);

    res.json({
      ...recipe[0],
      ingredients,
      steps,
      nutrition: nutrition[0] || null
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};
exports.searchRecipes = (req, res) => {
  // 处理逻辑
  res.send('搜索食谱');
};

// exports.recommendRecipes = (req, res) => {
//   // 处理逻辑
//   res.send('推荐食谱');
// };

// exports.analyzeNutrition = (req, res) => {
//   // 处理逻辑
//   res.send('营养分析');
// };

// // 模拟登录
// exports.login = (req, res) => {
//   const { username, password } = req.body;
//   // 这里应该有实际的用户验证逻辑
//   if (username === 'admin' && password === 'password') {
//     res.status(200).json({ message: '登录成功' });
//   } else {
//     res.status(401).json({ message: '用户名或密码错误' });
//   }
// };

// // 模拟食材识别
// exports.recognizeIngredients = (req, res) => {
//   if (!req.files || Object.keys(req.files).length === 0) {
//     return res.status(400).send('未上传任何文件。');
//   }

//   // 获取上传的文件
//   const image = req.files.image;

//   // 这里应该有实际的图片识别逻辑
//   res.status(200).json({ ingredients: ['苹果', '香蕉'] });
// };

// // 模拟营养分析
// exports.analyzeNutrition = (req, res) => {
//   const { recipeId } = req.query;
//   // 这里应该有实际的营养分析逻辑
//   res.status(200).json({ calories: 200, protein: 5, carbs: 30 });
// };

// // 模拟个性化推荐
// exports.personalizedRecommendations = (req, res) => {
//   // 这里应该有实际的个性化推荐逻辑
//   res.status(200).json({ recipes: ['苹果派', '香蕉奶昔'] });
// };
